package com.cimr.comm.util;

import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;


public class QueryUtil {
    public static Query and(Object...params) {
        Query query = new Query();

        final int N = params == null ? 0 : params.length / 2;
        for (int i = 0; i < N; i++) {
            Object key = params[i*2];
            Object value = params[i*2 + 1];
            if(key != null) {
                query.addCriteria(Criteria.where(key.toString()).is(value));
            }
        }
        return query;
    }

    public static Query or(Object...params) {
        Query query = new Query();
        List<Criteria> criterias = new ArrayList<Criteria>();

        final int N = params == null ? 0 : params.length / 2;
        for (int i = 0; i < N; i++) {
            Object key = params[i*2];
            Object value = params[i*2 + 1];
            if(key != null) {
                criterias.add(Criteria.where(key.toString()).is(value));
            }
        }
        Criteria[] criteriaArray = new Criteria[criterias.size()];
        criterias.toArray(criteriaArray);
        query.addCriteria(new Criteria().orOperator(criteriaArray));
        return query;
    }

    public static Update update(Object...params) {
        Update update = new Update();
        final int N = params == null ? 0 : params.length / 2;
        for (int i = 0; i < N; i++) {
            Object key = params[i*2];
            Object value = params[i*2 + 1];
            if(key != null) {
                update.set(key.toString(), value);
            }
        }
        return update;
    }
}
